<?php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');

    if (!function_exists('limit_text')) {

        /**
         * Shorten text for given number of character with preserved whole word
         */
        function limit_text($string, $length, $STRIP_TAGS = FALSE, $ADD_DOTS_ON_END = FALSE) {

            if (!isset($string) || $string == "")
                return "";

            if ($STRIP_TAGS)
                $string = strip_tags($string);

            if ($string == "")
                return "";

            $WidgetText = mb_substr($string, 0, strrpos(mb_substr($string, 0, $length), ' '));

            $WidgetText = trim($WidgetText);

            if ($WidgetText == "")
                return "";

            $chars = '.,;\'"0123456789';
            $last = mb_substr($WidgetText, -1);

            if ($ADD_DOTS_ON_END)
                if (strpos($chars, $last) === false)
                    $WidgetText.='...';
                else
                    $WidgetText = substr($WidgetText, 0, -1) . '...';

            return $WidgetText;
        }

    }